package cn.justforchris.user.controller;

import cn.justforchris.user.query.QueryPage;
import cn.justforchris.user.domain.User;
import cn.justforchris.user.service.IUserService;
import cn.justforchris.util.JsonResult;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;



@RestController
@RequestMapping("/user")
@Api(tags = "用户接口")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 新增
     * @param user
     * @return
     */
    @PutMapping
    public JsonResult insertOrUpdate(@RequestBody User user) {
       try {
        if (user.getId() == null) {
            userService.insertUser(user);
        } else {
            userService.updateUser(user);
        }
        return JsonResult.success();
       }catch (Exception e) {
           e.printStackTrace();
           return JsonResult.error();
       }
    }

    /**
     * 根据id删除数据
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public JsonResult deletUser(@PathVariable Long id){
        try{
            userService.deleteUser(id);
            return JsonResult.success();
        }catch (Exception e){
            e.printStackTrace();
            return JsonResult.error();
        }
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PatchMapping
    public JsonResult patchDelet(@RequestBody Long[] ids){
        try{
            userService.patchDelete(ids);
            return JsonResult.success();
        }catch (Exception e){
            e.printStackTrace();
            return JsonResult.error();
        }
    }

    /**
     * 根据id获取数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id){

        return userService.getUserById(id);

    }

    /**
     * 获取所有
     * @return
     */
    @GetMapping
    public List<User> getAll(){
        return userService.getAll();
    }

    /**
     * 分页查询
     * @param queryPage
     * @return
     */
    @PostMapping
    public PageInfo<User> queryPage(@RequestBody QueryPage queryPage){
        /*返回的数据是pagehelper的一个类,这个类创建的对象中储存的是查询出来的数据以及总条数(total)*/
        return userService.queryPage(queryPage);

    }







}
